package com.example.mailserver.receiver;

import com.example.common.model.Emp;
import com.example.common.model.MailConstants;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.util.SerializationUtils;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;

@Component
public class MailReceiver {
    private static final Logger logger = LoggerFactory.getLogger(MailReceiver.class);

    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    JavaMailSender javaMailSender;
    @Autowired
    MailProperties mailProperties;
    @Autowired
    TemplateEngine templateEngine;// thymeleaf 模板引擎

    //todo 还需要解决消费幂等性问题，一锁二判三更新
    @RabbitListener(queues = MailConstants.MAIL_QUEUE_NAME)
    public void mailReceiver(Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        byte[] body = message.getBody();
        Emp emp = (Emp) SerializationUtils.deserialize(body);
        String msgId = message.getMessageProperties().getHeader("spring_returned_message_correlation");


        try {
            // MimeMessageHelper支持发送复杂邮件模板，支持文本、附件、HTML、图片等
            MimeMessage msg = javaMailSender.createMimeMessage();
            // boolean multipart：是否支持发送附件
            MimeMessageHelper helper = new MimeMessageHelper(msg,true);

            helper.setFrom(mailProperties.getUsername());//设置发送人
            helper.setTo(Objects.requireNonNull(emp).getEmail());//设置收件人
            helper.setSubject("入职欢迎");//设置主题
            helper.setSentDate(new Date());//
            // 渲染 mail.html 文件为 字符串
            Context context = new Context();
            context.setVariable("name", emp.getName());
            context.setVariable("postName", emp.getPostName());
            context.setVariable("jobLevelName", emp.getJobLevelName());
            context.setVariable("departmentName", emp.getDepartmentName());
            String mail = templateEngine.process("mail", context);// thymeleaf 渲染 html 页面
            helper.setText(mail, true);//设置发送内容为 html 文本

            javaMailSender.send(msg);//发送
            channel.basicAck(deliveryTag, false);
            logger.info(msgId + ":邮件发送成功");
        } catch (Exception e) {
            channel.basicNack(deliveryTag,false,true);
            logger.error("邮件发送失败：" + e.getMessage());
        }

    }

}
